//
//  APIManager.m
//  KiklinkApp
//
//  Created by LF on 14-10-10.
//  Copyright (c) 2014年 Kiklink. All rights reserved.
//

#import "APIManager.h"
#import "AFHTTPRequestOperationManager.h"
#import "AccountManager.h"

NSString* mSessionId = @"";

NSString* const URL_BASE = @"http://www.kiklink.com:8080/";

@implementation APIManager

+ (AFHTTPRequestOperationManager *)AFManager
{
    AFHTTPRequestOperationManager *afManager = [AFHTTPRequestOperationManager manager];
    afManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    return afManager;
}


+(void) request:(NSString *) subURL
     parameters:(NSDictionary *) parameters
        success:(void (^)(AFHTTPRequestOperation*, id)) success
        failure:(void (^)(AFHTTPRequestOperation*, NSError*)) failure
{
    NSString* targetURL = [URL_BASE stringByAppendingString: subURL];
    [[self AFManager] GET:targetURL
               parameters:parameters
                  success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //Do somthing here.
         success(operation, responseObject);
     }
                  failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         failure(operation, error);
     }];
}

//包含通用化的错误处理
//已处理FAILURE_NETWORK_ERROR、FAILURE_EMPTY_RESULT、FAILURE_RETURN_ERRER_CODE三种情况，已处理的结果可原样返回
//已自动处理sessionId
+(void) requestWithoutRelogin:(NSString *) subURL
                   parameters:(NSDictionary *) parameters
                     callback:(Callback) callback
{
    if(parameters == nil)
    {
        parameters = [[NSDictionary alloc]init];
    }
    NSMutableDictionary *mutableParameters = [parameters mutableCopy];
    [mutableParameters setObject:mSessionId forKey:@"sessionId"];
    
    KLLogVerboseStringWithFormat(@"URL: %@", subURL);
    KLLogVerboseStringWithFormat(@"Param: %@", mutableParameters);
    
    [self request:subURL
       parameters:mutableParameters
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              
              if (responseObject == nil) {
                  NSString* word = [StatusCode getWordByCode:FAILURE_NO_JSON_OBJECT];
                  
                  KLLogStatic(self, word);
                  callback(FAILURE_NO_JSON_OBJECT, word, nil);
                  return;
              }
              
              NSNumber *re = [responseObject objectForKey:@"re"];
              if(re == nil)
              {
                  NSString* word = [StatusCode getWordByCode:FAILURE_PARSE_ERROR];
                  
                  KLLogStatic(self, word);
                  KLLogVerboseString(responseObject);
                  callback(FAILURE_PARSE_ERROR, word, responseObject);
                  return;
              }
              
              NSString* sessionId = [responseObject objectForKey:@"sessionId"];
              if(sessionId != nil)
              {
                  mSessionId = sessionId;
              }
              
              NSString* word = [responseObject objectForKey:@"word"];
              
              if ([re intValue] < 0)
              {
                  NSString *logWord = [NSString stringWithFormat:@"%@ %@: %@", [StatusCode getWordByCode:FAILURE_RETURN_ERRER_CODE], [re stringValue], word];
                  KLLogStatic(self, logWord);
                  KLLogVerboseString(responseObject);
                  
                  NSString *returnWord = [word stringByReplacingOccurrencesOfString:@" " withString:@"\n"];
                  
                  if([re intValue] == -100)
                  {
                      callback(FAILURE_NEED_LOGIN, returnWord, responseObject);
                      return;
                  }
                  
                  callback(FAILURE_RETURN_ERRER_CODE, returnWord, responseObject);
                  return;
              }
              
              KLLogStatic(self, [StatusCode getWordByCode:SUCCESS]);
              KLLogVerboseString(responseObject);
              callback(SUCCESS, word, responseObject);
          }
     
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSString* word = [StatusCode getWordByCode:FAILURE_NETWORK_ERROR];
              
              KLLogStatic(self, word);
              KLLogVerboseString(error);
              callback(FAILURE_NETWORK_ERROR, word , nil);
          }
     ];
}

+(void) request:(NSString *) subURL
     parameters:(NSDictionary *) parameters
       callback:(Callback) callback
{
    [self requestWithoutRelogin:subURL parameters:parameters callback:^(int stateCode, NSString *word, id content) {
        if (stateCode == FAILURE_NEED_LOGIN)
        {
            [AccountManager autoLoginKiklinkWithCallback:^(int stateCode, NSString *word, id content) {
                if(stateCode == SUCCESS)
                {
                    [self requestWithoutRelogin:subURL parameters:parameters callback:callback];
                }
                else
                {
                    callback(stateCode, word, content);
                }
            }];
        }
        else
        {
            callback(stateCode, word, content);
        }
    }];
}

@end
